############################################周星宏############################################
from django_redis import get_redis_connection
from rest_framework import serializers

from spits.models import Spit


class SpitAllSerializer(serializers.ModelSerializer):
    userid = serializers.IntegerField(read_only=True,label='userid')
    nickname = serializers.CharField(read_only=True,label='名字')
    avatar = serializers.CharField(read_only=True,label='吐槽用户地址')
    collected = serializers.SerializerMethodField(label='当前浏览⽤户是否收藏该吐槽')
    hasthumbup = serializers.SerializerMethodField(label='当前浏览⽤户是否点赞该吐槽')

    def get_nickname(self,obj):
        return obj.user.name
    def get_avatat(self,obj):
        return obj.user.avatar
    def get_collected(self,obj):
        user = self.context['request'].user
        redis_coon = get_redis_connection('myspit')
        collected = redis_coon.smembers(f'split_collection_{user.id}')
        if str(obj.id) in collected:
            return True
    def get_hasthumbup(self,obj):
        user = self.context['request'].user
        redis_coon = get_redis_connection('myspit')
        good = redis_coon.smembers(f'good_{user.id}')
        if str(obj.id) in good:
            return True




    class Meta:
        model = Spit
        fields = ('id','content','publishtime','userid','nickname','visits','thumbup','comment','avatar','collected','hasthumbup','parent')
        extra_kwargs = {
            'publishtime': {
                'read_only': True
        },
            'thumbup': {
                'read_only': True
        },
            'visits': {
                'read_only': True
        },
            'comment': {
                'read_only': True
        },
            'parent': {
                # 'read_only': True,
                'required': False,
                "allow_null": True
        }
        }
    def create(self, validated_data):
        user = self.context['request'].user
        parent = validated_data.get('parent')
        if parent:
            spits = Spit.objects.get(id=parent.id)
            spits.comment += 1
            spits.save()
        spit = Spit.objects.create(user=user,**validated_data)
        return spit
###########################################周星宏############################################